package com.imooc.service.impl;

import com.imooc.eo.SearchResumesEO;
import com.imooc.feign.UserMicroServiceFeign;
import com.imooc.pojo.ResumeEducation;
import com.imooc.pojo.ResumeExpect;
import com.imooc.pojo.ResumeWorkExp;
import com.imooc.result.GraceJSONResult;
import com.imooc.service.ResumeSearchService;
import com.imooc.service.ResumeService;
import com.imooc.utils.JsonUtils;
import com.imooc.utils.LocalDateUtils;
import com.imooc.vo.ResumeVO;
import com.imooc.vo.UsersVO;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.IdsQueryBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;
import org.springframework.data.elasticsearch.core.query.IndexQuery;
import org.springframework.data.elasticsearch.core.query.IndexQueryBuilder;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.Query;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author liansen
 * @create 06-15-23:37
 */
@Service
public class ResumeSearchServiceImpl implements ResumeSearchService {

    @Autowired
    private ElasticsearchRestTemplate esTemplate;

    @Autowired
    private ResumeService resumeService;

    @Autowired
    private UserMicroServiceFeign userMicroServiceFeign;



    @Override
    public void flashformAnfFlush(String userId) {
        //定义es对象
        SearchResumesEO resumesEO = new SearchResumesEO();

        //查询用户简历相关信息
        ResumeVO resume = resumeService.getResume(userId);

        //查询用户相关信息(远程调用)
        GraceJSONResult result = userMicroServiceFeign.get(userId);
        Object data = result.getData();
        String jsonStr = JsonUtils.objectToJson(data);
        UsersVO userInfo = JsonUtils.jsonToPojo(jsonStr, UsersVO.class);

        //把用户信息存入es对象中
        resumesEO.setUserId(userId);
        resumesEO.setNickname(userInfo.getNickname());
        resumesEO.setSex(userInfo.getSex());
        resumesEO.setFace(userInfo.getFace());
        LocalDate birthday = userInfo.getBirthday();
        String birthdayStr = LocalDateUtils.format(birthday, LocalDateUtils.DATE_PATTERN);
        resumesEO.setBirthday(birthdayStr);
        //计算年龄
        long years = LocalDateUtils.getChronoUnitBetween(userInfo.getBirthday(), LocalDate.now(), ChronoUnit.YEARS, true);
        resumesEO.setAge((int) years);

        //把简历相关信息存入es对象
        resumesEO.setSkills(resume.getSkills());
        resumesEO.setAdvantage(resume.getAdvantage());
        resumesEO.setAdvantageHtml(resume.getAdvantageHtml());
        resumesEO.setCredentials(resume.getCredentials());
        resumesEO.setJobStatus(resume.getStatus());
        resumesEO.setRefreshTime(LocalDateUtils.format(resume.getRefreshTime(), LocalDateUtils.DATETIME_PATTERN));
        //计算工作年限
        long workYears = LocalDateUtils.getChronoUnitBetween(userInfo.getStartWorkDate(), LocalDate.now(), ChronoUnit.YEARS, true);
        resumesEO.setWorkYears((int)workYears);

        //把最新就职的企业信息存入es对象(把工作经历存入es对象)
        List<ResumeWorkExp> workExpList = resume.getWorkExpList();
        Optional<ResumeWorkExp> max = workExpList.stream().max(Comparator.comparing(ResumeWorkExp::getBeginDate));
        ResumeWorkExp lastWork = max.get();
        resumesEO.setCompanyName(lastWork.getCompanyName());
        resumesEO.setPosition(lastWork.getPosition());
        resumesEO.setIndustry(lastWork.getIndustry());

        //把最近的教育经历存入es中
        List<ResumeEducation> educationList = resume.getEducationList();
        Optional<ResumeEducation> last = educationList.stream().max(Comparator.comparing(ResumeEducation::getBeginDate));
        ResumeEducation lastEdu = last.get();
        resumesEO.setSchool(lastEdu.getSchool());
        resumesEO.setEducation(lastEdu.getEducation());
        //专业名称
        resumesEO.setMajor(lastEdu.getMajor());

        //获得求职期望列表,每个求职期望对应一份简历
        List<ResumeExpect> expectList = resumeService.getMyResumeExpectList(resume.getId(), userId);
        for (ResumeExpect resumeExpect : expectList) {
            resumesEO.setResumeExpectId(resumeExpect.getId());
            resumesEO.setJobType(resumeExpect.getJobName());
            resumesEO.setCity(resumeExpect.getCity());
            resumesEO.setBeginSalary(resumeExpect.getBeginSalary());

            IndexQuery indexQuery = new IndexQueryBuilder().withObject(resumesEO).build();
            IndexCoordinates ic = IndexCoordinates.of("resume_result");
            esTemplate.index(indexQuery, ic);
        }

    }

    @Override
    public List<SearchResumesEO> searchCollectResumes(List<String> resumeExpectIds) {

        IdsQueryBuilder idsQueryBuilder = new IdsQueryBuilder();
        for (String resumeExpectId : resumeExpectIds) {
            idsQueryBuilder.addIds(resumeExpectId);
        }

        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        boolQueryBuilder.should(idsQueryBuilder);

        Query query = new NativeSearchQueryBuilder().withQuery(boolQueryBuilder).build();

        SearchHits<SearchResumesEO> result = esTemplate.search(query, SearchResumesEO.class);
        List<SearchHit<SearchResumesEO>> searchHits = result.getSearchHits();
        List<SearchResumesEO> collect = searchHits.stream().map(SearchHit::getContent).collect(Collectors.toList());
        return collect;
    }
}
